package com.frame.work.lib;

import com.alibaba.fastjson.JSONObject;
import com.frame.work.mqtt.Topic;
import com.frame.work.mqtt.data.handle.MqttDataHandle;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghui
 */
@Component
public class InfraredDeviceTimedTaskProcessor {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqttDataHandle mqttDataHandle;

    @Value("${topic.rabbit.generalQueueProcessing}")
    private String generalQueueProcessing;

    public void processFrame(String gatewayMac, String data) {
        //00写入成功
        String isSuccess = StringUtils.substring(data, data.length() - 2, data.length());
        String successStr = "00";

        //节点MAC地址
        String zigbeeDeviceMac = StringUtils.substring(data, 2, 18);
        //子索引2-4 分别表示定时任务 1、定时任务 2、定时任务 3
        String childIndex = StringUtils.substring(data, data.length() - 4, data.length() - 2);
        int taskIndex = Integer.parseInt(childIndex) - 1;

        //mqtt发送信息
        Map<String, Object> rep = new HashMap<>(5);
        rep.put("type", "timedTask");
        rep.put("gatewayMac", gatewayMac);
        rep.put("zigbeeMac", zigbeeDeviceMac);
        rep.put("code", isSuccess);
        rep.put("taskIndex", taskIndex);


        //若写入是否成功，需要发送rabbitmq，修改数据库
        if (isSuccess.equals(successStr)) {
            //发送rabbitmq
            Map<String, Object> information = new HashMap<>(3);
            information.put("dealType", "setTimedTask");
            information.put("zigbeeMac", zigbeeDeviceMac);
            information.put("taskIndex", taskIndex);
            rabbitTemplate.convertAndSend(generalQueueProcessing, information);
            System.out.println("发送定时任务rabbitmq");
        } else {
            mqttDataHandle.basePush(Topic.device.topics + gatewayMac + Topic.timedTask, JSONObject.toJSONString(rep));
        }
    }
}
